import React, { useState } from 'react';
import { Form, message, Radio, Select, Upload, Button, Input, Row } from 'antd';
import FormItem from '../../../components/FormItem';
import { connect } from 'react-redux';
import { APIUrl, APIUrlNoVersion } from '../../../services/createServices';
import { DATA_SOURCE } from '../../../utils/constant';
import { headerModules } from '../../../utils/utils';
import storage from '../../../utils/storage';
import services from '../../../services/api';
// import { debounce } from 'lodash';

const AddData = (props) => {
  const { namelist_data_type, form, closeModal, menu } = props;
  const [listOptions, setListOptions] = useState([]);
  // const [loading, setLoading] = useState(false);
  const [fileList, setFileList] = useState([]);

  const handleTypeChange = (value) => {
    if (value) {
      form.setFieldsValue({
        name_list_ids: [],
      });
      getNameList(value);
    } else {
      setListOptions([]);
    }
  };

  // 获取当前数据类型下的名单
  const getNameList = async (data_type) => {
    const { code, data, msg } = await services.nameList.searchNameList({ data_type });
    if (!code) {
      setListOptions(data);
    } else {
      message.error(msg);
    }
  };

  // const handleSearch = async (keyword) => {
  //   if (keyword) {
  //     const data_type = form.getFieldValue('data_type');
  //     setLoading(true);
  //     const { code, data, msg } = await services.nameList.searchNameList({ keyword, data_type });
  //     setLoading(false);
  //     if (!code) {
  //       setListOptions(data);
  //     } else {
  //       message.error(msg);
  //     }
  //   }
  // };

  const handleUploadChange = ({ fileList, file }) => {
    const { response, status } = file;
    setFileList(fileList);
    if (status === 'done') {
      const { code, data: file_code, msg } = response;
      if (!code) {
        form.setFieldsValue({ file_code });
        setFileList([file]);
      } else {
        form.setFieldsValue({ file_code: '' });
        setFileList([]);
        message.error(msg);
      }
    } else if (status === 'removed') {
      form.setFieldsValue({ file_code: '' });
      setFileList([]);
    } else {
      form.setFieldsValue({ file_code: '' });
    }
  };

  const handleSubmit = () => {
    form.validateFields(async (err, values) => {
      if (!err) {
        const { data_content } = values;
        values.data_content = data_content && data_content.split('\n').filter(Boolean);
        const { code, msg } = await services.nameList.addData(values);
        if (!code) {
          message.success(msg);
          closeModal();
        } else {
          message.error(msg);
        }
      }
    });
  };

  const getFormItems = () => {
    const layout = {
      labelCol: {
        span: 6,
      },
      wrapperCol: {
        span: 18,
      },
    };
    return [
      {
        label: {
          label: '数据类型',
          ...layout,
        },
        name: 'data_type',
        options: {
          initialValue: undefined,
          rules: [{ required: true, message: '请选择数据类型' }],
        },
        component: (
          <Select placeholder='请选择数据类型' onChange={handleTypeChange} style={{ width: '100%' }}>
            {namelist_data_type.map((item) => (
              <Select.Option value={item.key} key={item.key}>
                {item.value}
              </Select.Option>
            ))}
          </Select>
        ),
      },
      {
        label: {
          label: '选择名单',
          ...layout,
        },
        name: 'name_list_ids',
        options: {
          initialValue: [],
          rules: [{ required: true, message: '请选择名单' }],
        },
        component: (
          <Select
            mode='multiple'
            // showSearch
            placeholder='请输入名单'
            // defaultActiveFirstOption={false}
            // notFoundContent={loading ? <Spin size='small' /> : null}
            filterOption={(input, option) => option.props.children.includes(input)}
            // onSearch={debounce(handleSearch, 800)}
            style={{ width: '100%' }}
            showArrow={true}
          >
            {listOptions.map((item) => (
              <Select.Option value={item.name_list_id} key={item.name_list_id}>
                {item.list_name}
              </Select.Option>
            ))}
          </Select>
        ),
      },
      {
        label: {
          label: '添加数据',
          ...layout,
        },
        name: 'data_source',
        options: {
          initialValue: DATA_SOURCE._LOCAL,
          rules: [{ required: true, message: '请选择' }],
        },
        component: (
          <Radio.Group>
            <Radio value={DATA_SOURCE._LOCAL}>本地上传</Radio>
            <Radio value={DATA_SOURCE._COMSTOM}>手动录入</Radio>
          </Radio.Group>
        ),
      },
      form.getFieldValue('data_source') !== DATA_SOURCE._COMSTOM && {
        label: {
          label: '文件',
          ...layout,
        },
        name: 'file_code',
        options: {
          initialValue: undefined,
          rules: [{ required: true, message: '请上传文件' }],
        },
        component: (
          <div>
            <Upload
              accept='.xls,.xlsx'
              name='file'
              action={APIUrl + '/namelist/import'}
              showUploadList={{ showRemoveIcon: true, showDownloadIcon: false }}
              fileList={fileList}
              onChange={handleUploadChange}
              headers={{ 'X-User-Dept-Id': storage.dept, modules: headerModules(menu.asideHighlight) }}
            >
              <Button>上传文件</Button>
            </Upload>
            <p>
              支持扩展名 xls、xlsx，点击下载
              <a href={APIUrlNoVersion + '/common/template/namelist.xlsx'}>示例文件</a>
            </p>
          </div>
        ),
      },
      form.getFieldValue('data_source') === DATA_SOURCE._COMSTOM && {
        label: {
          label: '录入数据',
          ...layout,
        },
        name: 'data_content',
        options: {
          initialValue: '',
          rules: [{ required: true, message: '请填写数据内容' }],
        },
        component: (
          <Input.TextArea
            rows={4}
            placeholder='回车换行，每行一条记录，数据与备注用分号分割，&#10;如：192.168.0.1;备注内容&#10;192.168.0.2;备注内容'
          />
        ),
      },
    ].filter(Boolean);
  };

  return (
    <>
      {getFormItems().map((item, index) => (
        <FormItem key={index} form={form} item={item} colNum={1} />
      ))}
      <Row type='flex' justify='end' align='middle' className='params_button'>
        <Button onClick={closeModal} style={{ marginRight: '20px' }}>
          取消
        </Button>
        <Button type='primary' autoFocus={true} onClick={handleSubmit}>
          确定
        </Button>
      </Row>
    </>
  );
};

function mapStateToProps(state) {
  return {
    menu: state.menu,
  };
}

export default connect(mapStateToProps)(Form.create()(AddData));
